<template>
  <!-- 销售趋势 -->
  <a-card :loading="loading" :bordered="false" :body-style="{ padding: '0' }">
    <div class="salesCard">
      <a-tabs default-active-key="1" size="large" :tab-bar-style="{ marginBottom: '24px', paddingLeft: '16px' }">
        <!-- <template #rightExtra>
          <div class="extra-wrapper">
            <div class="extra-item">
              <a @click.prevent="fetchData('today')">今日</a>
              <a @click.prevent="fetchData('week')">本周</a>
              <a @click.prevent="fetchData('month')">本月</a>
              <a @click.prevent="fetchData('year')">本年</a>
            </div>
            <a-range-picker :style="{ width: '256px' }" />
            <a-button color="success">重置</a-button>
          </div>
        </template> -->
        <a-tab-pane loading="true" tab="铅封分布图" key="1">
          <a-row>
            <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24" style="padding: 20px; padding-top: 0">
              <maps :map-data="mapData"></maps>
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <RankList title="施封实时记录" :list="rankList" />
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane tab="施封统计表" key="2">
          <a-row>
            <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
              <BarMulti :chartData="barData" :option="{ title: { text: '', textStyle: { fontWeight: 'lighter' } } }" height="50vh" />
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <xian :chartData="GroupByRegion" height="50vh" @mapClick="handleMapClick" />
              <!-- 监听自定义事件 -->
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-card>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, watch } from 'vue';
  import BarMulti from '/@/components/chart/BarMulti.vue';
  import RankList from '/@/components/chart/RankList.vue';
  import xian from '/@/views/demo/charts/Xian.vue';
  import { useRootSetting } from '/@/hooks/setting/useRootSetting';
  import maps from '/@/views/demo/charts/map/Gaode.vue';
  import { getStationDetail, getlistnum, getSealLeadStatistics, getSealLeadGroupByRegion } from '/@/api/sys/user';

  defineProps({
    loading: {
      type: Boolean,
    },
  });

  const { getThemeColor } = useRootSetting();
  const rankList = ref([]); // 铅封数据
  const barData = ref([]); //图表数据
  const mapData = ref([]); // 地图数据
  const GroupByRegion = ref([]); // 区县地图数据
  const seriesColor = computed(() => getThemeColor.value);
  const chartData = ref([
    { name: '一月', value: 40, value1: 20 },
    { name: '二月', value: 21 },
    { name: '三月', value: 17 },
    { name: '四月', value: 13 },
    { name: '五月', value: 9 },
  ]);

  // 转换函数
  const transformData = (data: any[]) => {
    const mapData: { name: string; values: { value: number; tipData: string }[] }[] = [];

    data.forEach((item) => {
      const existingRegion = mapData.find((region) => region.name === item.regionCode_dictText);
      if (existingRegion) {
        existingRegion.values.push({ value: item.num, tipData: `${item.regionCode_dictText} ${item.position_dictText}` });
      } else {
        mapData.push({
          name: item.regionCode_dictText,
          values: [{ value: item.num, tipData: `${item.regionCode_dictText} ${item.position_dictText}` }],
        });
      }
    });

    return mapData;
  };

  // 用于从 API 获取数据的方法
  const fetchData = async (timeRange?: string) => {
    try {
      // 并行处理两个请求
      const [rankResponse, mapResponse, getechrt, quxianshuju] = await Promise.all([
        getStationDetail(), // 获取地图数据
        getlistnum(), // 获取10条数据
        getSealLeadStatistics(), // 获取按区施封统计
        getSealLeadGroupByRegion(), // 区县地图数据
      ]);
      // 更新 rankList 和 mapData
      // 铅封数据===
      rankList.value = mapResponse.records || [];
      // 地图数据==
      mapData.value = rankResponse || [];
      // 区县地图数据
      GroupByRegion.value = transformData(quxianshuju.records);
      console.log(GroupByRegion.value, '123111111');

      const transformedData = getechrt.flatMap((item) => {
        const positionMap = { 1: '编码器', 2: '流量计', 3: '主板' };
        const positionName = positionMap[item.position] || '未知';

        return [
          { name: '近1月安装情况', value: item.count1Month || 0, type: positionName },
          { name: '近3月安装情况', value: item.count3Month || 0, type: positionName },
          { name: '近6月安装情况', value: item.count6Month || 0, type: positionName },
          { name: '近1年安装情况', value: item.count12Month || 0, type: positionName },
          { name: '近2年安装情况', value: item.count24Month || 0, type: positionName },
          { name: '近3年安装情况', value: item.count36Month || 0, type: positionName },
        ];
      });

      barData.value = transformedData;
    } catch (error) {
      console.error('Failed to fetch data:', error);
    }
  };

  // 处理地图点击事件
  const handleMapClick = async (regionName: string) => {
    console.log('传来的name:', regionName);
    // 调用特定的 API 并传递 regionName 作为参数
    try {
      const response = await getSealLeadStatistics({ region: regionName });
      console.log('API Response:', response);
      // 根据 API 响应更新数据
      // 例如：rankList.value = response.records;
    } catch (error) {
      console.error('Failed to fetch seal lead statistics:', error);
    }
  };

  // 在组件挂载时请求数据
  onMounted(() => {
    fetchData();
  });
</script>

<style lang="less" scoped>
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }
</style>
